#!/bin/bash

echo "======================================"
echo "开始构建前后端整合jar包"
echo "======================================"

# 设置错误时退出
set -e

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
echo "脚本所在目录: $SCRIPT_DIR"
cd "$SCRIPT_DIR"

# 查找Maven命令
echo "步骤0: 查找Maven环境..."
MAVEN_CMD=""

# 尝试查找系统中的Maven
if command -v mvn >/dev/null 2>&1; then
    MAVEN_CMD="mvn"
    echo "- 找到系统 Maven: $(which mvn)"
elif command -v ./mvnw >/dev/null 2>&1; then
    MAVEN_CMD="./mvnw"
    echo "- 使用项目 Maven Wrapper: ./mvnw"
else
    # 尝试查找IDEA内置的Maven
    IDEA_MAVEN_PATHS=(
        "/Applications/IntelliJ IDEA.app/Contents/plugins/maven/lib/maven3/bin/mvn"
        "/Applications/IntelliJ IDEA CE.app/Contents/plugins/maven/lib/maven3/bin/mvn"
        "$HOME/Library/Application Support/JetBrains/Toolbox/apps/IDEA-U/ch-0/*/IntelliJ IDEA.app/Contents/plugins/maven/lib/maven3/bin/mvn"
        "$HOME/.m2/wrapper/dists/apache-maven-*/*/bin/mvn"
    )
    
    for maven_path in "${IDEA_MAVEN_PATHS[@]}"; do
        # 支持通配符匹配
        for expanded_path in $maven_path; do
            if [ -f "$expanded_path" ]; then
                MAVEN_CMD="$expanded_path"
                echo "- 找到IDE内置 Maven: $expanded_path"
                break 2
            fi
        done
    done
fi

if [ -z "$MAVEN_CMD" ]; then
    echo "❌ 未找到Maven，请安装Maven或者手动指定路径"
    echo ""
    echo "解决方案："
    echo "1. 安装Maven: brew install maven (在macOS上)"
    echo "2. 或者使用IDE构建功能直接在IntelliJ IDEA中构建"
    echo "3. 或者手动指定: export MAVEN_HOME=/path/to/maven"
    exit 1
else
    echo "- 使用Maven: $MAVEN_CMD"
fi

echo "步骤1: 清理之前的构建文件..."
# 清理前端构建文件
if [ -d "ruoyi-ui/dist" ]; then
    rm -rf ruoyi-ui/dist
    echo "- 清理前端dist目录"
fi

# 清理后端静态资源目录
if [ -d "ruoyi-admin/src/main/resources/static" ]; then
    rm -rf ruoyi-admin/src/main/resources/static
    echo "- 清理后端static目录"
fi

# 清理Maven构建文件
if [ -d "target" ]; then
    rm -rf target
    echo "- 清理根目录target"
fi

if [ -d "ruoyi-admin/target" ]; then
    rm -rf ruoyi-admin/target
    echo "- 清理ruoyi-admin/target"
fi

echo "步骤2: 构建前端项目..."
cd ruoyi-ui

# 检查node_modules是否存在，不存在则安装依赖
if [ ! -d "node_modules" ]; then
    echo "- 安装前端依赖..."
    npm install
fi

echo "- 构建前端生产版本..."
npm run build:prod

cd ..

echo "步骤3: 构建后端项目..."
$MAVEN_CMD clean package -DskipTests

echo "======================================"
echo "构建完成！"
echo "======================================"

# 查找生成的jar文件
JAR_FILE=$(find ruoyi-admin/target -name "ruoyi-admin.jar" -type f)

if [ -n "$JAR_FILE" ]; then
    echo "生成的jar文件位置: $JAR_FILE"
    echo ""
    echo "运行方式："
    echo "java -jar $JAR_FILE"
    echo ""
    echo "访问地址："
    echo "http://localhost:8085"
    echo ""
    echo "默认账号："
    echo "用户名: admin"
    echo "密码: admin123"
else
    echo "错误：未找到生成的jar文件！"
    exit 1
fi

echo "======================================"